package micro.web;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Exchanger;

/**
 * @author txw
 * @version V1.0
 * @Title: Test
 * @ProjectName micro-sleuth-server
 * @Description: 描述
 * @since 2018/7/4 22:09
 */
public class Test {
    Exchanger<Board> exchanger=new Exchanger<>();
    private final CyclicBarrier cyclicBarrier;
    private final Board mainBoard;
    private final Works[] works;
    public Test(Board board) {
        this.mainBoard=board;
        int count=Runtime.getRuntime().availableProcessors();
        cyclicBarrier=new CyclicBarrier(count, () -> System.out.println("值:"+mainBoard.calcValue()));
        this.works=new Works[count];
        for (int i=0;i<count;i++){
            works[i]=new Works(mainBoard.getNext(count,i));
        }
    }
    public class Works implements Runnable{
        private final Board board;
        public Works(Board board){
            this.board=board;
        }

        @Override
        public void run() {
            try {
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
    public void start(){
        for (Works work : works) {
            new Thread(work).start();
        }
    }
}
